前端开发经验总结-JavaScript 对象继承形式

JavaScript 对象继承形式

1. 对象冒充继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function A(name) {
this.name = name;
this.sayHello = function() {
alert(this.name + 'say Hello!');
};
}

function B(name, id) {
this.temp = A;
this.temp(name); // 相当于 new A();
delete this.temp; // 防止在以后通过 temp 引用覆盖超类 A 的属性和方法
this.id = id;
this.checkId = function(ID) {
alert(this.id === ID);
};
}

用 call 实现的对象冒充继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function Rect(width, height) {
this.width = width;
this.height = height;
this.area = function() {
return this.width * this.height;
};
}

function MyRect(width, height, name) {
Rect.call(this, width, height);
this.name = name;
this.show = function() {
alert(this.name + 'with area: ' + this.area());
}
}

2. 原型继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function Person() {
this.name = 'Mike';
this.sayGoodbye = function() {
alert('GoodBye!');
};
}

Person.prototype.sayHello = function() {
alert('Hello!');
};

function Student() {}
Student.prototype = new Person();
Student.prototype.constructor = Student;

3. 综合方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
var F = function() {};

function Person(name) {
this.name = name;
}
Person.prototype.sayHello = function() {
alert(this.name + 'say Hello!');
};

function Student(name, id) {
Person.call(this, name);
this.id = id;
}

F.prototype = Persion.prototype;
Student.prototype = new F();
Student.prototype.constructor = Student;
Student.uber = Persion.prototype; // 在子对象上打开一条通道,可以直接调用父对象的方法

Student.prototype.show = function() {
alert('Name is: ' + this.name + 'and Id is: ' + this.id);
}